<?php

use Core\AdminController;
use Models\Order;
use Models\Order_item;
use Models\Money_log;
use Models\Item;
use Models\Product;
use Models\OrderRefund;

class OrderController extends AdminController
{
	public function __construct()
	{
		parent::__construct();
		$this->lang->load('admin_order', $this->session->admin_language);
	}

	public function index()
	{
		$order = new Order;


		if($this->input->get('type') !== '' && $this->input->get('type') !== null){
			$order->where('type',$this->input->get('type'));
		}
		if($this->input->get('status')){
			if($this->input->get('status') == 10){
				$order->where('have_refund',1);
			}else{
				$order->where('orders.status',$this->input->get('status'));
			}

		}
		if ($this->input->get('order_id')) {
			$order->like('order_id', $this->input->get('order_id'));
		}
		if ($this->input->get('phone')) {
			$order->where('users.phone', $this->input->get('phone'));
		}
		if ($this->input->get('start_date')){
			$order->where('create_time >=',$this->input->get('start_date'));
		}
		if($this->input->get('end_date')){
			$order->where('create_time<=',$this->input->get('end_date'));
		}

		if ($this->input->get('with_delete')) {
			$order->default_filter(false);
			$order->where('orders.status in (1, 2, 3, 4, 5, 6, 7)');
		}

		$page = $order->select('orders.*, users.nickname')
			->join('users', 'users.id=orders.user_id','left')
			->order_by('id desc')
			->paginate(20);
		$this->load->view('admin/order/index', [
			'page' => $page
		]);
	}

	public function change_items(){
		$order = (new Order)->find($this->input->post('id'));
		$items = $this->input->post('item');
		$item_ids = $items['id'];
		$qtys = $items['qty'];
		$prices = $items['price'];

		$citems = [];
		$ctotal = 0;
		foreach ($item_ids as $i=>$id) {
			$citems[$id] = ['qty'=>$qtys[$i],'price'=>$prices[$i],'total'=>$qtys[$i]*$prices[$i]];
			$ctotal += $qtys[$i] * $prices[$i];
		}

		$order_items = $order->items();
		$total = 0;
		$product_ids = [];
		foreach ($order_items as $oi) {
			$total += $oi['qty']*$oi['price'];
			if(isset($citems[$oi['id']])){
				$ci = $citems[$oi['id']];
				if($oi['qty'] != $ci['qty'] || $ci['price'] != $oi['price']){

					(new Order_item)->update($oi['id'],$ci);
					//设置库存
					if($order['status'] == 1){
						$item = new Item;
						if($oi['qty'] > $ci['qty']){
							$item->increment('stock',$oi['item_id'],$oi['qty']-$ci['qty']);
							$item->decrement('solded',$oi['item_id'],$oi['qty']-$ci['qty']);
						}
						if($oi['qty'] < $ci['qty']){
							$item->decrement('stock',$oi['item_id'],$ci['qty']-$oi['qty']);
							$item->increment('solded',$oi['item_id'],$ci['qty']-$oi['qty']);
						}
						if($oi['qty'] != $ci['qty'] && !in_array($oi['product_id'],$product_ids)){
							$product_ids[] = $oi['product_id'];
						}
					}

				}
			}
		}

		if(!empty($product_ids)){
			(new Product)->stock($product_ids);
		}

		$user = $order->user();
		$reduce_money = $total - $ctotal;
		$data['total'] = $ctotal;
		if($order['status'] == 1){
			if($reduce_money > 0){
				//退货情况，返还至用户余额，添加退款金额
				$data['refund_fee'] = $order['refund_fee'] + $reduce_money;
				$data['remark'] = $order['remark'].' ['.date('Y-m-d').']设置商品数量和价格，退款：'.$reduce_money;
				if($user){
					$balance = $user['balance']+$reduce_money;
					$user->update($user['id'],['balance'=>$balance]);

					$money_log = new Money_log;
					$money_log['type'] = 4; //在线支付
					$money_log['user_id'] = $user['id'];
					$money_log['num'] = $reduce_money;
					$money_log['desc'] = 'System Refund';
					$money_log['create_time'] = date('Y-m-d H:i:s');
					$money_log->add();
				}
			}
			if($reduce_money < 0){
				//加货情况，减去用户余额，添加用户余额支付金额
				$data['money'] = $order['money']+abs($reduce_money);
				if($user){
					$balance = $user['balance'] - abs($reduce_money);
					if($balance<0) $balance = 0;
					$user->update($user['id'],['balance'=>$balance]);

					$money_log = new Money_log;
					$money_log['type'] = 0; //在线支付
					$money_log['user_id'] = $user['id'];
					$money_log['num'] = $reduce_money;
					$money_log['desc'] = 'System Pay';
					$money_log['create_time'] = date('Y-m-d H:i:s');
					$money_log->add();

				}
			}
		}

		$order->update($order['id'],$data);

	}

	// 管理员取消订单
	public function cancel($id)
	{
		$order = (new Order)->find($id);
		if (!$order) {
			$this->response(['error' => $this->lang->line('not found')], 404);
		}
		if (!in_array($order['status'], [0, 1])) {
			return $this->response(['error' => $this->lang->line('order can\'t cancel')], 422);
		}

		$order['status'] = 9;
		$order->update();

		return $this->response(['error' => 'success']);
	}

	public function detail($id)
	{
		$order = (new Order)->default_filter(false)->find($id);

		if (!$order) {
			show_404();
		}

		$items = $order->items();
		$user = $order->user();
		$address = $order->address();
		$cashier = $order->cashier();

		// 退换货情况

		$order_refunds = OrderRefund::where('order_id', $order['id'])
		->with([
            'user' => function ($query) {
                $query->select('id, first_name, last_name, balance');
            },
            'cashier' => function ($query) {
                $query->select('id, username');
            },
            'order' => function ($query) {
                $query->select('id, order_id');
            }
        ])
		->get();

		$pay_types = CONFIG('basic.pay_types');

		$this->load->view('/admin/order/detail', [
			'order' => $order,
			'items' => $items,
			'user' => $user,
			'address' => $address,
			'cashier' => $cashier,
			'order_refunds' => $order_refunds,
			'pay_types'=>$pay_types,
		]);
	}

	// 发货
	public function send($id)
	{
		$order = (new Order)->find($id);

		if (!$order) {
			show_404();
		}
		$order['status'] = 2;
		$order->update($order['id'],['status'=>2]);

		//设置进货记录库存
		$order->purchaseRecordStock($order['id']);

		return $this->response();
	}

	public function delete($id)
	{
		$order = (new Order)->find($id);
		$order->soft_delete();

		return $this->response();
	}
}
